package com.esun.cheetah.view.personal;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.personal.personalcommunicater.PersonalLoginCommunicater;
import com.esun.cheetah.biz.personal.personalcommunicater.RegistCommunicater;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.Key;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.view.HomeAct;
import com.esun.cheetah.view.setting.ServiceManager;
import com.esun.util.EditTextInputUitl;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;
import com.esun.util.md5.MD5;

/**
 * 
 * @Package com.esun.cheetah.view.personal.RegistAct
 * @ClassName: RegistAct
 * @Description: TODO(regist activity)
 * @author handy <br/>
 * @date create at 2012-7-31 下午3:02:38
 * 
 */
public class RegistAct extends Activity implements OnCheckedChangeListener,
		OnClickListener {

	private Button btnRegist; // 注册按钮
	private Button btnBack; // 返回..

	private EditText edtUserName; // 用户名
	private EditText edtUserPass; // 密码
	private EditText edtUserPhoneNum; // 手机号
	private TextView tvUserAgree; // 用户条款
	private Button btnCleanUserName; // 清空用户名..
	private Button btnCleanPassword; // 清空密码..
	private Button btnCleanMobile; // 清空手机号..

	private RegistCommunicater registCommunicater;
	private PersonalLoginCommunicater personallogincommunicater;
	private Handler loginhandler;
	private Handler registHandler;
	private String strUserName;
	private String strUserPass;
	private String strUserPassMD5;
	private String strUserPhoneNum;
	private SharedPreferences sharedPreferences;
	private Editor editor;
	private CheckBox cbxUserAgree; // 确认同意用户条款.
	private long loginTime; // 登陆时间
	public static boolean isRegistSucceed = false;
	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		// getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
		// WindowManager.LayoutParams. FLAG_FULLSCREEN);
		setContentView(R.layout.regist_act);
		uiInit();
		initHandler();
		progressDialog = ViewerUtil.showProgressDialog(RegistAct.this,
				"提交中请稍后...");
	}

	private void uiInit() {

		btnRegist = (Button) findViewById(R.id.registact_btn_regist);
		btnRegist.setOnClickListener(this);

		btnBack = (Button) findViewById(R.id.registact_btn_back);
		btnBack.setOnClickListener(this);

		edtUserName = (EditText) findViewById(R.id.registact_edt_userName);
		btnCleanUserName = (Button) findViewById(R.id.regist_btn_cleanusername);
		edtUserName = new EditTextInputUitl(edtUserName, btnCleanUserName)
				.getEditText();

		edtUserPass = (EditText) findViewById(R.id.registact_edt_userPass);
		btnCleanPassword = (Button) findViewById(R.id.regist_btn_cleanUserPass);
		edtUserPass = new EditTextInputUitl(edtUserPass, btnCleanPassword)
				.getEditText();

		edtUserPhoneNum = (EditText) findViewById(R.id.registact_edt_userPhone);
		btnCleanMobile = (Button) findViewById(R.id.regist_btn_cleanmobile);
		edtUserPhoneNum = new EditTextInputUitl(edtUserPhoneNum, btnCleanMobile)
				.getEditText();

		cbxUserAgree = (CheckBox) findViewById(R.id.registact_cbx_userAgree);
		cbxUserAgree.setOnCheckedChangeListener(this);
		cbxUserAgree.setChecked(true);

		tvUserAgree = (TextView) findViewById(R.id.registact_tv_userAgree);
		tvUserAgree
				.setText(Html
						.fromHtml("<a href=\"http://3g.500wan.com/help/terms.jsp\">《500WAN》服务条款</a>"));

		tvUserAgree.setMovementMethod(LinkMovementMethod.getInstance());

	}

	private void initHandler() {

		registHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					// saveSharedPreferences();
					startLoginCommunicate();
					break;
				case Config.COMMUNICATER_FAIL:
					// ViewerUtil.showTipDialog(RegistAct.this,
					// registCommunicater.getServerMsg(), false);
					Toast.makeText(RegistAct.this,
							registCommunicater.getServerMsg(), 500).show();
					progressDialog.cancel();
					break;
				case Config.COMMUNICATER_EXCEPTION:
					// btnRegist.setText("通讯异常");
					// ViewerUtil.showTipDialog(RegistAct.this,
					// Language.NERWORK_ABORT, false);
					Toast.makeText(RegistAct.this, Language.NERWORK_ABORT, 500)
							.show();
					progressDialog.cancel();
					EDebug.o("通讯异常" + UserInfo.getUserInfo().getCk());
					break;
				default:
					break;

				}
			}
		};

		loginhandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					EDebug.o("abc" + UserInfo.getUserInfo().getFreezemoney());
					EDebug.o("abc" + UserInfo.getUserInfo().getMoney());
					saveSharedPreferences();
					saveUserInfo();
					gotoLoggedin();
					progressDialog.cancel();
					break;
				case Config.COMMUNICATER_FAIL:
					// ViewerUtil.showTipDialog(RegistAct.this,
					// personallogincommunicater.getServerMsg(), false);
					// tv_please_login.setText("返回信息不正确");
					Toast.makeText(RegistAct.this,
							personallogincommunicater.getServerMsg(), 500)
							.show();
					progressDialog.cancel();
					EDebug.o("返回信息不正确"
							+ UserInfo.getUserInfo().getFreezemoney());
					break;
				case Config.COMMUNICATER_EXCEPTION:
					// tv_please_login.setText("通讯异常");
					progressDialog.cancel();
					// ViewerUtil.showTipDialog(RegistAct.this,
					// personallogincommunicater.getServerMsg(), false);
					Toast.makeText(RegistAct.this,
							personallogincommunicater.getServerMsg(), 500)
							.show();
					EDebug.o("通讯异常" + UserInfo.getUserInfo().getFreezemoney());
					break;
				default:
					break;
				}
			}
		};
	}

	private void saveUserInfo() {
		loginTime = System.currentTimeMillis();
		UserInfo.getUserInfo().setLogintime(loginTime);
		EDebug.o("logintime------" + loginTime);
	}

	private void gotoLoggedin() {
		Intent intent = new Intent();
		intent.setClass(RegistAct.this, HomeAct.class);
		PersonalAct.flag = Language.FLAG_SIX;
		HomeAct.flag = Language.FLAG_ONE;
		startActivity(intent);
		RegistAct.this.finish();
	}

	private void startLoginCommunicate() {
		personallogincommunicater = new PersonalLoginCommunicater(loginhandler,
				strUserName, strUserPassMD5, this);
		personallogincommunicater.startCommunicate();
		openNotice();
	}

	private void saveSharedPreferences() {
		sharedPreferences = getSharedPreferences(Key.SHAREDPREFERENCES_NAME,
				Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();
		editor.putString(Key.KEY_USERNAME, strUserName);
		editor.putString(Key.SAVE_PASSWORD, strUserPassMD5);
		editor.commit();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.registact_btn_regist:
			// 验证输入限制条件
			if (!edtUserName.getText().equals(null)
					&& edtUserName.getText().toString().length() < Language.NUM_ONE) {
				// ViewerUtil.showTipDialog(this, Language.ENTER_USERNAME,
				// false);
				Toast.makeText(this, Language.ENTER_USERNAME, 500).show();
			} else if (!edtUserPass.getText().equals(null)
					&& edtUserPass.getText().toString().length() < Language.NUM_ONE) {
				// ViewerUtil.showTipDialog(this,
				// Language.ENTER_REGIST_PASSWORD,
				// false);
				Toast.makeText(this, Language.ENTER_REGIST_PASSWORD, 500)
						.show();
			} else if (!edtUserPhoneNum.getText().equals(null)
					&& edtUserPhoneNum.getText().toString().length() < Language.NUM_ONE) {
				// ViewerUtil.showTipDialog(this, Language.ENTER_PHONENUM,
				// false);
				Toast.makeText(this, Language.ENTER_PHONENUM, 500).show();
			} else if (!(edtUserPhoneNum.getText().toString().length() == Language.NUM_ELEVEN)) {
				// ViewerUtil.showTipDialog(this, Language.ENTER_RIGHT_PHONENUM,
				// false);
				Toast.makeText(this, Language.ENTER_RIGHT_PHONENUM, 500).show();
			} else if (edtUserName.getText().toString().length() < Language.NUM_FOUR
					|| edtUserName.getText().toString().length() > Language.NUM_SIXTEEN) {
				// ViewerUtil.showTipDialog(this, Language.ENTER_RIGHT_USERNAME,
				// false);
				Toast.makeText(this, Language.ENTER_RIGHT_USERNAME, 500).show();
			} else if (edtUserPass.getText().toString().length() < Language.NUM_SIX
					|| edtUserPass.getText().toString().length() > Language.NUM_FIVETEEN) {
				// ViewerUtil.showTipDialog(this, Language.ENTER_RIGHT_PASSWORD,
				// false);
				Toast.makeText(this, Language.ENTER_RIGHT_PASSWORD, 500).show();
			} else {
				getInputInfo();
				startRegistCommunicater();
				progressDialog.show();
			}
			break;
		case R.id.registact_btn_back:
			gotoLogin();
			break;
		default:
			break;
		}
	}

	private void startRegistCommunicater() {
		registCommunicater = new RegistCommunicater(registHandler, this,
				strUserName, strUserPass, strUserPhoneNum);
		registCommunicater.startCommunicate();
	}

	private void getInputInfo() {
		strUserName = edtUserName.getText().toString();
		strUserPass = edtUserPass.getText().toString();
		strUserPassMD5 = MD5.md5(strUserPass);
		strUserPhoneNum = edtUserPhoneNum.getText().toString();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

		switch (buttonView.getId()) {
		case R.id.registact_cbx_userAgree:
			if (isChecked) {
				btnRegist.setEnabled(true);
			} else {
				btnRegist.setEnabled(false);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 捕捉返回键动作
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			gotoLogin();
			return true;
		}
		return false;
	}

	private void gotoLogin() {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setClass(RegistAct.this, HomeAct.class);
		HomeAct.flag = Language.FLAG_ONE;
		PersonalAct.flag = Language.FLAG_FIVE;
		startActivity(intent);
		RegistAct.this.finish();
	}

	/**
	 * 开启push通知
	 */
	private void openNotice() {
		ServiceManager serviceManager = new ServiceManager(this);
		serviceManager.setNotificationIcon(R.drawable.notification);
		serviceManager.startService();

	}
}
